package com.xiaomei.manager.weixin.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import com.xiaomei.manager.weixin.util.MD5Util;



public class WXSignUtils {
	    
	    //商户Key		
		private static String Key = "abcdefABCDEF01234567890123456789";

		/**
		 * 微信支付签名算法sign
		 * @param characterEncoding
		 * @param parameters
		 * @return
		 */
		@SuppressWarnings("rawtypes")
		public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
			StringBuffer sb = new StringBuffer();
			Set es = parameters.entrySet();//所有签名的参数按照accsii排序（升序）
			Iterator it = es.iterator();
			while(it.hasNext()) {
				Map.Entry entry = (Map.Entry)it.next();
				String k = (String)entry.getKey();
				Object v = entry.getValue();
				if(null != v && !"".equals(v) 
						&& !"sign".equals(k) && !"key".equals(k)) {
					sb.append(k + "=" + v + "&");
				}
			}
			sb.append("key=" + Key);
			System.out.println("字符串拼接后是："+sb.toString());
			String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
			System.out.println("sign:"+sign);
			return sign;
		}
				
	    
	    public static String getNonceStr() {
			Random random = new Random();
			return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
		}

		public static String getTimeStamp() {
			return String.valueOf(System.currentTimeMillis() / 1000);
		}
	    
}
